package cn.ac.cintcm.prespring.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * 给每个以name:elementName,elementName2...为行的每个元素赋予编号项
 * @author 何前锋 Franklin He(franklinheqf@gmail.com)
 *
 */
public class NumberAllocation {
    private IndexFile index;
    private NameIndex elements;
    private NameIndex items;
    private HashMap<String, Integer> itemsIndex;
    private HashMap<String, Integer> elementsIndex;
    
    public NumberAllocation() {
        index = new IndexFile();
        itemsIndex = new HashMap<String, Integer>();
        elementsIndex = new HashMap<String, Integer>();
    }
    
    public void allocateNumber(String s) {
        List<String> list = new ArrayList<String>();
        String item = FileUtil.parseLineStr(s, list);
        Integer itemInt = itemsIndex.get(item);
        if (itemInt == null) {
            itemInt = itemsIndex.size() + 1;
            itemsIndex.put(item, itemInt);
        }
        
        List<Integer> ea = new ArrayList<Integer>();
        for (String e : list) {
            Integer elementInt = elementsIndex.get(e);
            if (elementInt == null) {
                elementInt = elementsIndex.size() + 1;
                elementsIndex.put(e, elementInt);
            }
            ea.add(elementInt);
        }
        
        Arrays.sort(ea.toArray(new Integer[0]));
        index.getIdListIndex().put(itemInt, ea);
        
    }

    public NameIndex getElements() {
        elements = new NameIndex();
        HashMap<Integer, String> indexName = elements.getIdName();
        for (String s : elementsIndex.keySet()) {
            indexName.put(elementsIndex.get(s), s);
        }
        return elements;
    }

    public void setElements(NameIndex elements) {
        this.elements = elements;
    }

    public IndexFile getIndex() {
        return index;
    }

    public void setIndex(IndexFile index) {
        this.index = index;
    }

    public NameIndex getItems() {
        items = new NameIndex();
        HashMap<Integer, String> indexName = items.getIdName();
        for (String s : itemsIndex.keySet()) {
            indexName.put(itemsIndex.get(s), s);
        }
        return items;
    }

    public void setItems(NameIndex items) {
        this.items = items;
    }


}
